﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading;
using DotNetAgent.Core;
using System.Xml;

namespace DotNetAgent
{
    public partial class DotNetAgentService : ServiceBase
    {
        Agent _Agent;
        protected Timer StateTimer;
        protected TimerCallback TimerDelegate;

		public DotNetAgentService()
        {
        }

		public void StartAgent(object Args)
		{
			try
			{
				FileLogConnector.DebugLog("Creating & Starting Agent: " + ((String)Args));
				_Agent = Agent.CreateAgent(null,Args as Dictionary<String, Object>);
			}
			catch (Exception Ex)
			{
				FileLogConnector.DebugLog("Error While Starting Agent", Ex);
				//throw new AgentException("StartAgent", "Error While Starting Agent", Ex);
			}
		}

        protected override void OnStart(string[] args)
        {
            try
            {
				FileLogConnector.DebugLog("OnStart Acknowledged");
				XmlDocument doc = new XmlDocument();
				doc.Load("agent.xml");
				
				TimerDelegate = new TimerCallback(StartAgent);
                StateTimer = new Timer(	TimerDelegate,
										doc.OuterXml,
										0,
										System.Threading.Timeout.Infinite);
				FileLogConnector.DebugLog("Scheduled Agent Start");
            }
            catch (Exception Ex)
            {
				FileLogConnector.DebugLog("Error While Starting", Ex);
                //throw new AgentException("OnStart", "Error While Starting", Ex);
            }
        }


        protected override void OnStop()
        {
            try
            {
				FileLogConnector.DebugLog("OnStop Acknowledged");
				_Agent.Dispose();
				FileLogConnector.DebugLog("Stopped Agent");
				if (StateTimer != null)
                {
                    StateTimer.Dispose();
                }
                TimerDelegate = null;
                StateTimer = null;
				FileLogConnector.DebugLog("Stopped");
			}
            catch (Exception Ex)
            {
				FileLogConnector.DebugLog("Error While Stopping", Ex);
				//throw new AgentException("OnStop", "Error While Stopping", Ex);
            }
        }
    }
}
